package com.mp.approvalreq.util;

import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.entity.Template;
import com.mp.approvalreq.entity.dto.TemplateDTO;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.mp.user.util.UserUtils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TemplateUtils {

    /**
     * 判断报销模板是否是新版本的报销模板
     */
    public static boolean isNewExpenseTemplate(int templateType, Request req) {
        if (templateType != Template.EXPENSES) {
            return false;
        }

        String totalMoney = req.getTotalMoney();
        return totalMoney != null;
    }


    public static List<Integer> getTemplateIds(List<TemplateDTO> templateDTOS) {
        return templateDTOS.stream().map(TemplateDTO::getTemplateId).collect(Collectors.toCollection(() -> new ArrayList<>(templateDTOS.size())));
    }

    public static List<TemplateDTO> filterTemplatesByUser(User user, List<TemplateDTO> templateDTOs) throws Throwable {
        if (UserUtils.isAdmin(user)) {
            return templateDTOs;
        }
        // 当前身份的deptIds
        List<String> userDeptIds = ListHelper.string2StringList(user.getDeptPath());
        // 所有身份的deptIds
        List<String> allMultiUserDeptIds = getAllMultiUserDeptIds(user.getCompanyId(), user.getCompanyInfoId());

        return templateDTOs.stream().filter(templateDTO -> hasPermissionTemplate(user, templateDTO, userDeptIds, allMultiUserDeptIds)).collect(Collectors.toList());
    }

    private static boolean hasPermissionTemplate(User user, TemplateDTO templateDTO, List<String> userDeptIds, List<String> allMutiUserDeptIds) {
        // 全公司范围
        if (ApprovalUtils.isAllCompanyRange(templateDTO.getDepartmentIds())) {
            return true;
        }

        // 指定某些部门和指定某些人范围: 1. 仅选部门; 2: 选了部门又选了指定人
        if (ApprovalUtils.isSpecifiedDepts(templateDTO.getDepartmentIds())) {
            if (ApprovalUtils.isMoreTemplateType(templateDTO.getDefaultType())) {
                List<String> deptIds = ListHelper.string2StringList(templateDTO.getDepartmentIds());
                if (ListHelper.hasEqualsElement(allMutiUserDeptIds, deptIds)) {
                    return true;
                }

                if (isPermitWithMoreIdentity(user, templateDTO.getCompanyInfoIdRange())) {
                    return true;
                }
            }

            List<String> specifiedDeptIds = ListHelper.string2StringList(templateDTO.getDepartmentIds());
            if (ListHelper.hasEqualsElement(userDeptIds, specifiedDeptIds)) {
                return true;
            }

            if (isPermit(user, templateDTO.getSpecificRange())) {
                return true;
            }
        }

        // 指定人范围
        if (ApprovalUtils.isSpecificRange(templateDTO.getDepartmentIds())) {
            if (ApprovalUtils.isMoreTemplateType(templateDTO.getDefaultType())) {
                if (isPermitWithMoreIdentity(user, templateDTO.getCompanyInfoIdRange())) {
                    return true;
                }
            }

            return isPermit(user, templateDTO.getSpecificRange());
        }

        return false;
    }

    private static boolean isPermitWithMoreIdentity(User user, String companyInfoIdRange) {
        if (StringUtils.isEmpty(companyInfoIdRange)) {
            return false;
        }

        for (String companyInfoId : companyInfoIdRange.split(",")) {
            if (companyInfoId.equals(user.getCompanyInfoId().toString())) {
                return true;
            }
        }

        return false;
    }

    private static boolean isPermit(User user, String specificRange) {
        if (StringUtils.isEmpty(specificRange)) {
            return false;
        }

        for (String contactId : specificRange.split(",")) {
            if (contactId.equals(user.getContactId().toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param companyId
     * @param companyInfoId
     * @return
     * @throws Throwable
     */
    private static List<String> getAllMultiUserDeptIds(Integer companyId, Integer companyInfoId) throws Throwable {
        UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);
        List<User> users = userService.getMultiUserListByCompanyInfoId(companyId, companyInfoId);

        List<String> deptPath = new ArrayList<>();
        for (User user : users) {
            deptPath.addAll(ListHelper.string2StringList(user.getDeptPath()));
        }

        return deptPath;
    }

    public static Map<Integer, Template> getTemplateMap(List<Template> templates) {
        return templates.stream().collect(Collectors.toMap(Template::getTemplateId, t -> t, (a, b) -> b));
    }
}
